package com.cn.springcloudwechat.controller.shop;

import com.cn.springcloudwechat.common.utils.HttpPostUtil;
import com.cn.springcloudwechat.common.utils.XMLParser;
import com.cn.springcloudwechat.common.weiXinPay.sortUntil.SortUtil;
import com.cn.springcloudwechat.common.weiXinPay.weiXinSina.Sina;
import com.cn.springcloudwechat.common.weiXinPay.xmlUntil.XMLUtil;
import com.cn.springcloudwechat.controller.shop.WeiXinPayConfig;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.*;

public class WeiXinPay {

	/**
	 * 微信公众号支付返回mweb_url
	 * @方法名:pay
	 * @描述:
	 * @param body
	 * @param total_fee
	 * @return
	 */
	public Map<Object,Object> pay(String body, int total_fee,String openid,String orderId) {
		Map<Object,Object> maps = new HashMap<>();
		SortedMap<Object,Object> params = new TreeMap<Object,Object>();
		//		// 创建需要转换的对象
		WeiXinPayConfig weiXinPayConfig = new WeiXinPayConfig(body, total_fee,openid,orderId);
        System.out.println("weixin:->"+weiXinPayConfig.toString());
		SortedMap<Object,Object> beanToMap = SortUtil.beanToMap(weiXinPayConfig);
		String sign = Sina.createSign(beanToMap);
		weiXinPayConfig.setSign(sign);
		// 将对象转换成string类型的xml
		String str = XMLUtil.convertToXml(weiXinPayConfig);
		System.out.println(str+"=======");
		// 调用下单接口
		String result = HttpPostUtil.sendPost(WeiXinPayConfig.pay_url, str);
		System.err.println(result);
		// 接受的微信返回数据
		Map<String, Object> map;
		String payUrl = "";
		String prepay_id = "";
		try {
			map = XMLParser.getMapFromXML(result);
			System.out.println(map.toString()+"+++++++++++");
			if (map.get("return_code").equals("SUCCESS") && map.get("return_msg").equals("OK")) {
				String timeStamp = String.valueOf(System.currentTimeMillis()/1000);
				params.put("appId", map.get("appid"));
				params.put("timeStamp",timeStamp);
				params.put("nonceStr",weiXinPayConfig.getNonce_str());
				params.put("package", "prepay_id="+map.get("prepay_id"));
				params.put("signType","MD5");
				String paySign = Sina.createSign(params);
				params.put("paySign",paySign);
				System.out.println("签名->"+paySign);
				params.put("pg","prepay_id="+map.get("prepay_id"));
                params.put("type", "shop");
				System.out.println(params);
//				SlfRecharge slfRecharge = new SlfRecharge();
//				slfRecharge.setOrderNumber("23511");
//				slfRechargeMapper.insertSlfRecharge(slfRecharge);
			} else if (map.get("return_code").equals("NOTENOUGH")) {
				// 用户余额不足
//				throw new
			} else if ("ORDERPAID".equals(map.get("err_code"))) {
				// 商户订单已支付，无需重复操作
			} else if ("SYSTEMERROR".equals(map.get("err_code"))) {
				// 系统超时
			} else if ("ORDERCLOSED".equals(map.get("err_code"))) {
				// 参数中缺少APPID
			} else if ("APPID_NOT_EXIST".equals(map.get("err_code"))) {
				// 当前订单已关闭，无法支付
			} else if ("MCHID_NOT_EXIST".equals(map.get("err_code"))) {
				// 参数中缺少MCHID
			} else if ("APPID_MCHID_NOT_MATCH".equals(map.get("err_code"))) {
				// appid和mch_id不匹配
			} else if ("LACK_PARAMS".equals(map.get("err_code"))) {
				// 缺少必要的请求参数
			} else if ("OUT_TRADE_NO_USED".equals(map.get("err_code"))) {
				// 同一笔交易不能多次提交
			} else if ("SIGNERROR".equals(map.get("err_code"))) {
				// 参数签名结果不正确
			} else if ("XML_FORMAT_ERROR".equals(map.get("err_code"))) {
				// XML格式错误
			} else if ("REQUIRE_POST_METHOD".equals(map.get("err_code"))) {
				// 未使用post传递参数
			} else if ("POST_DATA_EMPTY".equals(map.get("err_code"))) {
				// post数据不能为空
			} else if ("NOT_UTF8".equals(map.get("err_code"))) {
				// 未使用指定编码格式
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*
		 * WeiXinPayConfig weiXinPayConfig1 = (WeiXinPayConfig)
		 * XMLUtil.convertXmlStrToObject(WeiXinPayConfig.class, str);
		 * System.out.println(weiXinPayConfig1); System.out.println(
		 * "---将String类型的xml转换成对象 End---");
		 */
		params.put("orderId",orderId);
		return params;
	}


	/**
	 * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
	 * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
	 *
	 * @return ip
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		System.out.println("x-forwarded-for ip: " + ip);
		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if( ip.indexOf(",")!=-1 ){
				ip = ip.split(",")[0];
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			System.out.println("Proxy-Client-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			System.out.println("WL-Proxy-Client-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
			System.out.println("HTTP_CLIENT_IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
			System.out.println("X-Real-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			System.out.println("getRemoteAddr ip: " + ip);
		}
		System.out.println("获取客户端ip: " + ip);
		return "171.88.45.106";
	}


	/**
	 * 获取随机字符串
	 * @return
	 */
	public static String getNonce_str() {
		String nonce_str = UUID.randomUUID().toString().trim().replaceAll("-", "");
		return nonce_str;
	}

	public static String setXML(String return_code, String return_msg) {
		return "<xml><return_code><![CDATA[" + return_code
				+ "]]></return_code><return_msg><![CDATA[" + return_msg
				+ "]]></return_msg></xml>";

	}

	public static void main(String[] args) {
	}
}
